/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */

package yams.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 微信工具类
 * Created by Luffy on 2017/8/6.
 */
public class WeixinUtil {

    public final static String OPEN_ID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    public final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    public final static String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info";
    public final static String MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send";
    public final static String PREORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    public final static String GROUP_URL = "https://api.weixin.qq.com/cgi-bin/groups";
    public final static String ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    public final static String CONFIG_APPID = "wxf3e1063abaf889ab";
    public final static String CONFIG_MCH_ID = "1426008302";
//    public final static String CONFIG_SECRET = "511e4629bb152201fe939e1665d132c7";
    public final static String CONFIG_SECRET = "9c71766b86c4d1a56caa90aa9dac8eb4";
    public final static String CONFIG_KEY = "hzklppglyxgskywlwkjyxgszhwftdbz0";


    public static Long TOKEN_TIME = 7000000L ; //jsapi_ticket的有效期为7200秒，我们在这里提前2s
    public static String TOKEN_CACHE_TOKEN_ID = "tokenId";
    public static Long TOKEN_CACHE_TOKEN_TIME = 0L ;

    /**
     * 获取token
     * @throws IOException
     */
/*    public static String getAccessToken() throws IOException {

        Long n = System.currentTimeMillis();
        if (n - TOKEN_CACHE_TOKEN_TIME > TOKEN_TIME) {
            String token_url = TOKEN_URL+"?appid="+CONFIG_APPID
                    +"&secret="+CONFIG_SECRET+"&grant_type=client_credential";

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(token_url);
            CloseableHttpResponse response = httpclient.execute(httpGet);

            try {
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(is, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer buffer = new StringBuffer();
                String str;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                is.close();
                JSONObject jsonObject = JSONObject.parseObject(buffer.toString());
                TOKEN_CACHE_TOKEN_ID = jsonObject.get("access_token").toString();
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }

            TOKEN_CACHE_TOKEN_TIME = n;

        }

        return TOKEN_CACHE_TOKEN_ID;

    }*/

    /**
     * 获取token
     * @throws IOException
     */
    public static String getAccessToken() throws IOException {
        Long n = System.currentTimeMillis();
        if (n - TOKEN_CACHE_TOKEN_TIME > TOKEN_TIME){
            String requestUrl="http://wx.keepright.cn:1980/api/getWeChatTokenString?token=17e89c10-7d55-4b0f-86c9-1eda54b29c5d";

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(requestUrl);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            try {
                HttpEntity resEntity = response.getEntity();
                InputStream resIs = resEntity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(resIs, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                StringBuffer buffer = new StringBuffer();
                String str;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                resIs.close();

                TOKEN_CACHE_TOKEN_ID   = buffer.toString();

                EntityUtils.consume(resEntity);

            } finally {
                response.close();
            }
            TOKEN_CACHE_TOKEN_TIME = n;
        }
        return TOKEN_CACHE_TOKEN_ID;
    }

}
